package com.hswealth;

import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.Random;
import java.util.Vector;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.WindowConstants;

public class GameFrame extends JFrame{
	
	HeroPlane heroPlane;
	
	GameFrame gameFrame;
	
	//创建子弹的集合
	Vector<Bullet> bullets = new Vector<>();
	//创建子弹的集合
	Vector<EnemyPlane> enemyPlanes = new Vector<>();
	
	public GameFrame() {
		gameFrame = this;
		//创建英雄机
		heroPlane = new HeroPlane();
		heroPlane.start();
		//设置窗体的宽高
		this.setSize(335,590);
		//标题
		this.setTitle("雷霆战机");
		this.setResizable(false);
		this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
		this.setLocationRelativeTo(null);
		//窗口可见
		this.setVisible(true);
		
		
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				while (true) {
					repaint();
					try {
						Thread.sleep(10);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}).start();
		
		//产生敌机的线程
		new Thread(new Runnable() {
			Random random = new Random();
			@Override
			public void run() {
				while(true) {
					EnemyPlane enemyPlane = new EnemyPlane(random.nextInt(500),0,gameFrame);
					enemyPlane.start();
					enemyPlanes.add(enemyPlane);
					
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				
			}
		}).start();
	}
	
	/**
	 * 在窗口上画，paint方法在窗口初始化时会默认执行	
	 */
	public void paint(Graphics g) {
//		System.out.println("绘制画板");
		//画背景
		BufferedImage image = (BufferedImage) this.createImage(this.getSize().width, this.getSize().height);
		//高效缓存的画笔
		Graphics pain = image.getGraphics();
		//画背景
		pain.drawImage(new ImageIcon("img/hsbackground.jpg").getImage(), 0, 0, null);
		//画飞机
		pain.drawImage(heroPlane.img, heroPlane.x, heroPlane.y, heroPlane.height, heroPlane.width, null);
		//画我方飞机子弹
		for (int i = 0; i < bullets.size(); i++) {
			Bullet bullet = bullets.get(i);
			if (bullet.y > 0) {
				pain.drawImage(bullet.img, bullet.x, bullet.y -= bullet.speed, bullet.height, bullet.width, null);
			}
			else {
				bullets.remove(bullet);
			}
		}
		//画敌方飞机
		for (int i = 0; i < enemyPlanes.size(); i++) {
			EnemyPlane enemyPlane = enemyPlanes.get(i);
			
			if (enemyPlane.y < 590) {
				pain.drawImage(enemyPlane.img, enemyPlane.x, enemyPlane.y += enemyPlane.speed, enemyPlane.height, enemyPlane.width, null);
			}
			else {
				enemyPlanes.remove(enemyPlane);
			}
		}
		
		//生效
		g.drawImage(image, 0, 0, null);
	}
	
	public static void main(String[] args) {
		GameFrame frame = new GameFrame();
		Player player = new Player(frame);
		frame.addKeyListener(player);
	}

}
